<template>
  <a-layout>

    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">

      <a-form
          layout="inline"
          :model="state"
      >
        <a-form-item>
          <a-input v-model:value="state.name" placeholder="name">
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="load">select</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="add">create</a-button>
        </a-form-item>
      </a-form>

      <a-table :columns="columns" :data-source="ebook"
               :pagination="pagination"
               @change="handleTableChange">

        <template #bodyCell="{ column,record }">

          <template v-if = "column.key === 'cover'">
            <img v-if = "record.cover" :src="record.cover" style="width: 50px;height: 50px">
          </template>

          <template v-else-if="column.key === 'category'">
            {{getCategoryName(record.category1Id) }}/{{ getCategoryName(record.category2Id) }}
          </template>

          <template v-else-if="column.key === 'action'">
            <a-space>
              <router-link :to="'/adminDoc?ebookId='+record.id">
                <a-button type="primary" @click="">viewDoc</a-button>
              </router-link>

              <a-button type="primary" @click="update(record)">update</a-button>

              <a-popconfirm
                    title="Are you sure delete this record?"
                    ok-text="Yes"
                    cancel-text="No"
                    @confirm="confirmDel(record.id)"
                    @cancel="cancel"
                >
                <a-button type="primary" danger >Delete</a-button>
              </a-popconfirm>
            </a-space>
          </template>

        </template>
      </a-table>

    </a-layout-content>


    <div>
      <a-modal
          v-model:visible="visible"
          title="Title"
          :confirm-loading="confirmLoading"
          @ok="handleOk"
      >
        <p>
          <a-form :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol">

            <a-form-item label="Ebook Name">
              <a-input v-model:value="formState.name" />
            </a-form-item>

            <a-form-item label="Ebook Category">
              <a-cascader
                  v-model:value="categoryIds"
                  :field-names="{ label: 'name', value: 'id', children: 'children' }"
                  placeholder="请选择!!!"
                  :options="level"
              />
            </a-form-item>

            <a-form-item label="Ebook Cover">
              <a-input v-model:value="formState.cover" />
            </a-form-item>

            <a-form-item label="Ebook Description">
              <a-input v-model:value="formState.description" />
            </a-form-item>

            <a-form-item label="Ebook DocCount">
              <a-input v-model:value="formState.docCount" />
            </a-form-item>

            <a-form-item label="Ebook ViewCount">
              <a-input v-model:value="formState.viewCount" />
            </a-form-item>

            <a-form-item label="Ebook VoteCount">
              <a-input v-model:value="formState.voteCount" />
            </a-form-item>

          </a-form>
        </p>
      </a-modal>
    </div>

  </a-layout>
</template>

<script>
import axios from "axios";
import {ref, onBeforeMount } from "vue"
import { message } from 'ant-design-vue'
import {arrayToTree} from "@/util/Tool";

export default {
  name: "AdminEbook",
  setup(){
    const ebook = ref()
    const columns  = ref([
      {
        title: 'name',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: 'category',
        key: 'category',
        dataIndex: 'category',
      },
      {
        title: 'cover',
        dataIndex: 'cover',
        key: 'cover',
      },
      {
        title: 'description',
        dataIndex: 'description',
        key: 'description',
      },
      {
        title: 'docCount',
        dataIndex: 'docCount',
        key: 'docCount',
      },
      {
        title: 'viewCount',
        key: 'viewCount',
        dataIndex: 'viewCount',
      },
      {
        title: 'voteCount',
        key: 'voteCount',
        dataIndex: 'voteCount',
      },
      {
        title: 'action',
        key: 'action',
        dataIndex: 'action',
      },
    ])
    const pagination = ref({
      current:1,
      pageSize:2,
      total:''
    })
    const visible = ref(false);
    const confirmLoading = ref(false);
    const formState = ref({})
    const state = ref({})
    const level = ref();
    const categoryIds = ref([])
    let categories = []

    onBeforeMount(()=>{
      console.log("onMounted AdminEbook")
      load()
      loadCategory()

    })

    function load() {
      console.log("load...")

      axios.get("api/ebookList", {
        params: {
          pageNum: pagination.value.current,
          pageSize: pagination.value.pageSize,
          name:state.value.name,
        }
      }).then(res => {
        console.log(res)
        if(res.data.code === "200"){
          ebook.value = res.data.data.list
          pagination.value.current = res.data.data.pageNum
          pagination.value.pageSize = res.data.data.pageSize
          pagination.value.total = res.data.data.total
        }else{
          message.error(res.data.msg)
        }
      })
    }

    function loadCategory(){
      console.log("loadCategory...")
      axios.get("api/categoryList")
          .then(res=>{
            categories = res.data.data
            console.log("categories")
            console.log(categories)
            level.value = arrayToTree(res.data.data,0)
            console.log(level.value)

          })
    }

    const getCategoryName = (categoryId) =>{

      console.log("getCategoryName")
      for(let i=0;i<categories.length;i++){

        let category = categories[i]
        if(categoryId == category.id){
          console.log(category.name)
          return category.name
        }
      }
    }

    function handleTableChange(pagination2) {
      console.log("handleTableChange")
      pagination.value = pagination2
      load()
    }

    const update = (record) => {
      formState.value = JSON.parse(JSON.stringify(record))

      categoryIds.value[0] = record.category1Id.toString()
      categoryIds.value[1] = record.category2Id.toString()

      visible.value = true
    };

    const add = () => {
      formState.value = {}
      categoryIds.value = []
      visible.value = true
    };

    const confirmDel = (id) => {
      console.log("confirmDel")


      axios.delete("api/ebook/"+id,)
          .then(res => {
            console.log(res.data.code)

            if(res.data.code === "200"){
              console.log(res.data.msg)

              message.success(res.data.msg);
              load()
            }else{
              console.log(res.data.msg)
              message.error(res.data.msg);
            }
          })
    };

    const handleOk = () => {
      console.log("handleOk")

      formState.value.category1Id = categoryIds.value[0]
      formState.value.category2Id = categoryIds.value[1]

      confirmLoading.value = true
      axios.post("api/ebook",formState.value)
          .then(res => {
            console.log(res.data.code)

            if(res.data.code === "200"){
              visible.value = false
              confirmLoading.value = false
              load()
            }else{
              message.error(res.data.msg);
            }
          })
      confirmLoading.value = false
      // load()
    }

    return{
      ebook,
      columns,
      pagination,
      visible,
      confirmLoading,
      formState,
      state,
      level,
      categoryIds,
      labelCol: {
        style: {
          width: '150px',
        },
      },
      wrapperCol: {
        span: 14,
      },
      update,
      add,
      handleOk,
      handleTableChange,
      confirmDel,
      load,
      loadCategory,
      getCategoryName
    }
  }
}
</script>

<style scoped>

</style>